package com.xczz.controller;

import com.xczz.common.Result;
import com.xczz.common.base.BaseController;
import com.xczz.common.constant.UserConstants;
import com.xczz.common.result.RestResult;
import com.xczz.common.result.TableDataInfo;
import com.xczz.model.SysUser;
import com.xczz.model.vo.SysUserVO;
import com.xczz.service.SysRoleService;
import com.xczz.service.SysUserService;
import com.xczz.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/users")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService roleService;

    @GetMapping(value = {"/","/{userId}"})
    public RestResult getInfo(@PathVariable(value = "userId",required = false) Long userId){
        RestResult ajax=RestResult.success();
        ajax.put("roles",roleService.selectRoleAll());
        if(StringUtils.isNotNull(userId)){
            ajax.put(RestResult.DATA_TAG,sysUserService.selectUserById(userId));
            ajax.put("roleIds",roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }
//    // 获取所有用户
//    @GetMapping
//    public Result<List<SysUser>> getAllUsers() {
//        List<SysUser> users = sysUserService.getAllUsers();
//        return Result.success(users);
//    }

    // 根据ID获取用户
//    @GetMapping("/{userId}")
//    public Result<SysUser> getUserById(@PathVariable Long userId) {
//        Optional<SysUser> user = sysUserService.getUserById(userId);
//        return user.map(Result::success).orElseGet(() -> Result.error(404, "用户不存在"));
//    }

//    // 创建用户
//    @PostMapping
//    public Result<SysUserEntity> createUser(@RequestBody SysUserEntity user) {
//        SysUserEntity createdUser = sysUserService.createUser(user);
//        return Result.success(createdUser);
//    }

//    // 更新用户
//    @PutMapping("/{userId}")
//    public Result<SysUser> updateUser(@PathVariable Long userId, @RequestBody SysUser user) {
//        user.setUserId(userId); // 确保ID一致
//        SysUser updatedUser = sysUserService.updateUser(userId, user);
//        return Result.success(updatedUser);
//    }

    @PutMapping
    public RestResult edit(@Validated @RequestBody SysUserVO user){
        user.setUpdateBy("system");
        boolean flag=sysUserService.updateUser(user);
        return toAjax(flag?1:0);
    }
    // 删除用户
//    @DeleteMapping("/{userId}")
//    public Result<Void> deleteUser(@PathVariable Long userId) {
//        sysUserService.deleteUser(userId);
//        return Result.success(null);
//    }

    @DeleteMapping("/{userIds}")
    public RestResult remove(@PathVariable Long[] userIds){
        return toAjax(sysUserService.deleteUserByIds(userIds));
    }
    //添加用户
    @PostMapping
    public RestResult add(@RequestBody SysUserVO user){
        if(UserConstants.NOT_UNIQUE.equals(sysUserService.checkUserNameUnique(user.getUserName()))){
            return RestResult.error("新增用户"+user.getUserName()+"失败，登录账号已存在");
        } else if(UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(user))){
            return RestResult.error("新增用户"+user.getUserName()+"失败，手机号码已存在");
        } else if(UserConstants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(user))){
            return RestResult.error("新增用户"+user.getUserName()+"失败，邮箱账号已存在");
        }
        user.setCreateBy("admin");
        boolean flag=sysUserService.insertUser(user);
        return toAjax(flag ? 1:0);
    }

    //分页查询
    @GetMapping("/list")
    public TableDataInfo list(SysUserVO user, Pageable page){
        int pageNum=page.getPageNumber()-1;
        pageNum=pageNum<=0?0:pageNum;
        page= PageRequest.of(pageNum,page.getPageSize());
        return sysUserService.selectUserList(user,page);
    }
}